<?php
/**
 * Created by PhpStorm.
 * User: yulin
 * Date: 2018/8/22
 * Time: 17:56
 */

namespace app\open\controller;
use app\open\model;
use app\adminapi\model\User;
use app\adminapi\validate\Report;
use app\adminapi\validate\BeidouValidate;
use app\open\validate;
/**
 * @name【9.小程序相关】
 * @baseurl【open/Wechat】
 * @file【Wechat.php】
 */

class Wechat extends Base
{
    /**
     * 生成盐
     * @return bool|string
     */
    protected function genSalt(){
        return substr(uniqid(), -6);
    }

    /**
     * 北斗用的，获取redis数据
     */
    public function getRedisData()
    {
        $prefix = '*beidou*';
        $ret = $this->redis->keys($prefix);
        if (empty($ret)) {
            return $this->retError(123);
        }
        $brr = [];
        $nowTime = time();
        foreach ($ret as $v) {
            $arr = $this->redis->get($v);
            $arr = json_decode($arr, true);
            $arr['time'] - $nowTime > 15 * 60 && $arr['alarm'] = '终端没电';
            $arr['time'] - $nowTime > 15 * 60 && $arr['state'] = ' 停止 离线 不定位';
            $brr[] = $arr;
        }
        return $brr;
    }

    /**
     * @name【1.1登录】
     * @desc【登录】
     * @uri【onLogin】
     * @method【post】
     * @table【p_user,p_passenger,p_company】
     * @param【
     * code $ string $ abc $ 微信登录code  #
     * username $ string $ abc $ 鹏程出行账号  #
     * password $ string $ abc $ 鹏程出行密码  #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * 】
     * @return mixed|\think\response\Json|void
     * @throws \app\base\exception\RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function onLogin()
    {
        $params = input('param.');

        $data = [];
        $data['wx_code'] = $params['code'];
        $data['username'] = $params['username'];
        $data['password'] = $params['password'];

        $appid = 'wx24904e62cc36f197';
        $secret = '555c5ac0ec1777228c99bd6e530464f2';

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $data['wx_code'] . '&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $wxreturn = curl_exec($ch);
        $wxreturn = json_decode($wxreturn);
        $wxreturn = get_object_vars($wxreturn);
        curl_close($ch);
        $data['session_key'] = $wxreturn['session_key'];
        $data['openid'] = $wxreturn['openid'];
        $data['unionid'] = $wxreturn['unionid'];
        $data['errcode'] = $wxreturn['errcode'];
        $data['errmsg'] = $wxreturn['errmsg'];


        if ($data['openid'] && !$params['username'] && !$params['password']) {
            $user_return = (new model\User())
                ->where('openid', $data['openid'])
                ->whereNull('delete_time')
                ->find();
            $passenger_return = (new model\Passenger())
                ->where('user_id', $user_return['user_id'])
                ->find();
            $company_return = (new model\Company())
                ->where('company_id', $user_return['company_id'])
                ->find();
            if ($user_return) {
                if ($user_return['state'] !== 1) {
                    $data['msg'] = '用户已被禁用#1';
                    $code = 0;
                }
                else {
                    $data['user_id'] = $user_return['user_id'];
                    $data['mobile'] = $user_return['mobile'];
                    $data['role_id'] = $user_return['role_id'];
                    $data['state'] = $user_return['state'];
                    $data['company_id'] = $user_return['company_id'];
                    $data['username'] = $user_return['username'];
                    $data['name'] = $passenger_return['name'];
                    $data['passenger_id'] = $passenger_return['passenger_id'];
                    $data['company_name'] = $company_return['company_name'];
                    $data['msg'] = '微信登录成功#1';
                    $code = 1;
                }
            }
            else {
                $data['msg'] = '该微信未绑定鹏程出行#1';
                $code = 0;
            }
        }
        elseif ($params['username'] && $params['password'] && !$data['openid']) {
            $user_return = (new model\User())
                ->where('username', $params['username'])
                ->whereNull('delete_time')
                ->field('*')
                ->find();
            if ($user_return['state'] !== 1) {
                $data['msg'] = '用户已被禁用#2';
                $code = 0;
            }
            elseif (!$user_return || CorePwd($params['password'], $user_return['salt']) != $user_return['password']) {
                $data['msg'] = '用户名或密码错误#2';
                $code = 0;
            }
            else {
                $company_return = (new model\Company())
                    ->where('company_id', $user_return['company_id'])
                    ->find();
                $passenger_return = (new model\Passenger())
                    ->where('user_id', $user_return['user_id'])
                    ->find();
                $data['user_id'] = $user_return['user_id'];
                $data['mobile'] = $user_return['mobile'];
                $data['role_id'] = $user_return['role_id'];
                $data['state'] = $user_return['state'];
                $data['company_id'] = $user_return['company_id'];
                $data['username'] = $user_return['username'];
                $data['name'] = $passenger_return['name'];
                $data['passenger_id'] = $passenger_return['passenger_id'];
                $data['company_name'] = $company_return['company_name'];
                $data['msg'] = '账号登录成功#2';
                $code = 1;
            }
        }
        elseif ($params['username'] && $params['password'] && $data['openid']) {
            $user_return = (new model\User())
                ->where('username', $params['username'])
                ->whereNull('delete_time')
                ->find();
            if ($user_return['state'] !== 1) {
                $data['msg'] = '用户已被禁用#3';
                $code = 0;
            } elseif (!$user_return || CorePwd($params['password'], $user_return['salt']) != $user_return['password']) {
                $data['msg'] = '用户名或密码错误#3';
                $code = 0;
            } else {
                $company_return = (new model\Company())
                    ->where('company_id', $user_return['company_id'])
                    ->find();
                $passenger_return = (new model\Passenger())
                    ->where('user_id', $user_return['user_id'])
                    ->find();
                $data['user_id'] = $user_return['user_id'];
                $data['mobile'] = $user_return['mobile'];
                $data['role_id'] = $user_return['role_id'];
                $data['state'] = $user_return['state'];
                $data['company_id'] = $user_return['company_id'];
                $data['username'] = $user_return['username'];
                $data['name'] = $passenger_return['name'];
                $data['passenger_id'] = $passenger_return['passenger_id'];
                $data['company_name'] = $company_return['company_name'];
                if ($data['openid'] && $data['wx_code']) {
                    (new model\User())
                        ->where('user_id', $data['user_id'])
                        ->update(['openid' => $data['openid']]);
                    $data['msg'] = '账号登录成功,微信绑定成功#3';
                    $code = 1;
                } elseif ($data['wx_code']) {
                    $data['msg'] = '账号登录成功,微信绑定失败#3';
                    $code = 1;
                } else {
                    $data['msg'] = '账号登录成功#3';
                    $code = 1;
                }
            }
        }

        $data['code'] = $code;
        $data['time'] = time();
        return json($data);
    }

    /**
     * @name【1.2退出登录】
     * @desc【退出登录】
     * @uri【logout】
     * @method【post】
     * @table【p_user】
     * @param【
     * user-token $ string $ c59d9b9ae1475d42c9f44bde41b68856 $ user-token，放置在请求头中 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * 】
     * @return \think\response\Json
     * @throws BaseException
     */
    public function logout(){
        $userToken = $this->request->header('user-token');
        $data = [];
        if(!$userToken){
            $data['msg'] = '缺少user-token';
            $code = 0;
        }

        (new User())->logout($userToken);

        $data['code'] = $code;
        $data['time'] = time();
        return json($data);
    }

    /**
     * @name【1.3修改密码】
     * @desc【修改密码】
     * @uri【edit】
     * @method【post】
     * @table【p_user】
     * @param【
     * user_id $ int $ 123 $ 用户id $ 1 #
     * password_old $ string $ abc $ 旧密码 $ 1 #
     * password_new $ string $ abc $ 新密码 $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * 】
     * @return mixed|\think\response\Json|void
     * @throws \app\base\exception\RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $params = input('param.');

        $data = [];
        $data['user_id'] = $params['user_id'];
        $data['password_old'] = $params['password_old'];
        $data['password_new'] = $params['password_new'];
        $user_return = (new model\User())
            ->where('user_id', $data['user_id'])
            ->whereNull('delete_time')
            ->find();
        if(!$user_return || CorePwd($data['password_old'],$user_return['salt']) != $user_return['password']){
            $data['msg'] = '旧密码错误';
            $code = 0;
        }
        elseif($data['password_new']){
            $salt = $this->genSalt();
            $data['password_new'] = CorePwd($data['password_new'], $salt);
            (new model\User())
                ->where('user_id', $data['user_id'])
                ->update(['password' => $data['password_new'],'salt' => $salt]);
            $data['msg'] = '更改密码成功';
            $code = 1;
        }
        else{
            $data['msg'] = '登录失败,或缺少新密码';
            $code = 0;
        }

        $data['code'] = $code;
        $data['time'] = time();
        return json($data);

    }

    /**
     * @name【1.4解除绑定】
     * @desc【解除绑定】
     * @uri【deleteOpenid】
     * @method【post】
     * @table【p_user】
     * @param【
     * openid $ string $ abc $ 绑定的微信openid $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * 】
     * @return mixed|\think\response\Json|void
     * @throws \app\base\exception\RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function deleteOpenid()
    {
        $params = input('param.');

        $data = [];
        $data['openid'] = $params['openid'];

        if($data['openid']) {
            $user_return = (new model\User())
                ->where('openid', $data['openid'])
                ->whereNull('delete_time')
                ->find();
            if($user_return) {
                $user_return = (new model\User())
                    ->where('openid', $data['openid'])
                    ->update(['openid' => '']);
                if($user_return) {
                    $data['msg'] = '解绑成功';
                    $code = 1;
                }
                else{
                    $data['msg'] = '解绑失败,请联系管理员';
                    $code = 0;
                }
            }
            else{
                $data['msg'] = '查无此openid';
                $code = 0;
            }
        }
        else{
            $data['msg'] = '请输入openid';
            $code = 0;
        }

        $data['code'] = $code;
        $data['time'] = time();
        return json($data);

    }

    /**
     * @name【1.5发送模板(暂时别用，还缺点东西)】
     * @desc【发送模板】
     * @uri【sendMsg】
     * @method【post】
     * @table【】
     * @param【
     * touser $ string $ abc $ 接收者（用户）的 openid $ 1 #
     * template_id $ string $ abc $ 所需下发的模板消息的id $ 1 #
     * page $ string $ abc $ 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。 #
     * form_id $ string $ abc $ 表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id $ 1 #
     * data $ string $ abc $ 模板内容，不填则下发空模板 $ 1 #
     * emphasis_keyword $ string $ abc $ 模板需要放大的关键词，不填则默认无放大 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * 】
     * @return mixed|\think\response\Json|void
     * @throws \app\base\exception\RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendMsg()
    {
        $params = input('param.');

        $data = [];

        $appid = 'wx24904e62cc36f197';
        $secret = '555c5ac0ec1777228c99bd6e530464f2';
        //获取access_token
        $url1 = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_URL, $url1);
        curl_setopt($ch1, CURLOPT_HEADER, false);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        $access_tokenreturn = curl_exec($ch1);
        $access_tokenreturn = json_decode($access_tokenreturn);
        $access_tokenreturn = get_object_vars($access_tokenreturn);
        curl_close($ch1);
        $access_token = $access_tokenreturn['access_token'];

        //访问发送模板消息的API
        $post_data = [];
        $params['touser'] && $post_data['touser'] = $params['touser'];
        $params['template_id'] && $post_data['template_id'] = $params['template_id'];
        $params['page'] && $post_data['page'] = $params['page'];
        $params['form_id'] && $post_data['form_id'] = $params['form_id'];
        $params['emphasis_keyword'] && $post_data['emphasis_keyword'] = $params['emphasis_keyword'];
        $params['keyword1'] && $post_data['data']['keyword1']['value'] = $params['keyword1'];
        $params['keyword2'] && $post_data['data']['keyword2']['value'] = $params['keyword2'];
        $params['keyword3'] && $post_data['data']['keyword3']['value'] = $params['keyword3'];
        $params['keyword4'] && $post_data['data']['keyword4']['value'] = $params['keyword4'];
        $params['keyword5'] && $post_data['data']['keyword5']['value'] = $params['keyword5'];
        $params['keyword6'] && $post_data['data']['keyword6']['value'] = $params['keyword6'];
        $params['keyword7'] && $post_data['data']['keyword7']['value'] = $params['keyword7'];
        $params['keyword8'] && $post_data['data']['keyword8']['value'] = $params['keyword8'];
        $params['keyword9'] && $post_data['data']['keyword9']['value'] = $params['keyword9'];
        $params['keyword10'] && $post_data['data']['keyword10']['value'] = $params['keyword10'];
        $post_data = json_encode($post_data);

        $url2 = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
        $ch2 = curl_init();
        curl_setopt($ch2, CURLOPT_URL, $url2);
        curl_setopt($ch2, CURLOPT_HEADER, false);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch2, CURLOPT_POST, 1);
        curl_setopt($ch2, CURLOPT_POSTFIELDS, $post_data);
        $wxreturn = curl_exec($ch2);
        $wxreturn = json_decode($wxreturn);
        $wxreturn = get_object_vars($wxreturn);
        curl_close($ch2);

        $data['errcode'] = $wxreturn['errcode'];
        $data['errmsg'] = $wxreturn['errmsg'];
        if($data['errcode'] == 0){
            $data['msg'] = '发送成功';
            $code = 1;
        }
        else{
            $data['msg'] = '发送失败';
            if($data['errcode'] == 40003){
                $data['msg'] = '不合法的 OpenID，请开发者确认OpenID否是其他小程序的 OpenID';
            }
            if($data['errcode'] == 40037){
                $data['msg'] = 'template_id不正确';
            }
            if($data['errcode'] == 41028){
                $data['msg'] = 'form_id不正确，或者过期';
            }
            if($data['errcode'] == 41029){
                $data['msg'] = 'form_id已被使用';
            }
            if($data['errcode'] == 41030){
                $data['msg'] = 'page不正确';
            }
            if($data['errcode'] == 45009){
                $data['msg'] = '接口调用超过限额（目前默认每个帐号日调用限额为100万）';
            }
            $code = 0;
        }

        $data['code'] = $code;
        $data['time'] = time();
        return json($data);
    }

    /**
     * @name【2.1改变订单状态】
     * @desc【改变订单状态】
     * @uri【changeOrderState】
     * @method【post】
     * @table【p_rder,p_passenger】
     * @param【
     * order_id $ int $ 123 $ 订单ID $ 1 #
     * order_state $ string $ abc $ 订单新状态 $ 1 #
     * approval_id $ int $ 123 $ 审核人ID $ 1 #
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * 】
     * @return mixed|\think\response\Json|void
     * @throws \app\base\exception\RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeOrderState()
    {
        $params = input('param.');

        $data = [];
        $data['order_id'] = $params['order_id'];
        $data['order_state'] = $params['order_state'];
        $data['approval_id'] = 0;
        $data['approval_id'] = $params['approval_id'];
        if($data['order_id'] && $data['order_state'] == '3'){
            (new model\Order())->where('order_id', $data['order_id'])->update(['order_state' => $data['order_state']]);
            $data['msg'] = '订单状态更改为:已拒绝';
            $code = 1;
        }
        elseif($data['order_id'] && $data['order_state'] == '1' && $data['approval_id'] > 0){
            $passenger_return = (new model\Passenger())->where('passenger_id', $data['approval_id'])->where('is_check', 1)->whereNull('delete_time')->find();
            if($passenger_return) {
                (new model\Order())->where('order_id', $data['order_id'])->where('order_state', $data['order_state'])->update(['approval_id' => $passenger_return['passenger_id'],'approval' => $passenger_return['name']]);
                $data['msg'] = '审核员更改更改为:'.$passenger_return['name'];
                $code = 1;
            }
            else{
                $data['msg'] = '不存在该审核人,或者该用户不具有审核权限';
                $code = 0;
            }
        }
        elseif($data['order_id'] && $data['order_state'] == '2' && $data['approval_id'] > 0){
            $passenger_return = (new model\Passenger())->where('passenger_id', $data['approval_id'])->where('is_check', 1)->whereNull('delete_time')->find();
            if($passenger_return) {
                (new model\Order())->where('order_id', $data['order_id'])->update(['approval_id' => $passenger_return['passenger_id'],'approval' => $passenger_return['name'],'order_state' => '2']);
                $data['msg'] = '订单状态更改为:已批准';
                $code = 1;
            }
            else{
                $data['msg'] = '不存在该审核人,或者该用户不具有审核权限';
                $code = 0;
            }
        }
        else{
            $data['msg'] = '未知错误,请联系管理员';
            $code = 0;
        }

        $data['code'] = $code;
        $data['time'] = time();
        return json($data);
    }

    /**
     * @name【2.2提交订单申请】
     * @desc【提交订单申请】
     * @uri【orderApply】
     * @method【post】
     * @table【p_passenger】
     * @param【
     * token $ string $ token $ 校验码 $ 1#
     * car_type_id $ string $ 1 $ 车辆类型，2：优选型，3：舒适型，4：豪华型，5：小巴，6：中巴，7：大巴，8：执法车 $ 1#
     * order_type $ string $ 1 $ 订单类型 订单类型,1：公务订单，2：企业订单，3：个人订单 $ 1#
     * passenger_name $ string $ 小猪啊 $ 乘客姓名 $ 1#
     * passenger_phone $ string $ 17689 $ 乘客电话 $ 1#
     * orderer_name $ string $ 小猫啊 $ 下单人 $ 1#
     * from_addr $ string $ 石狮 $ 出发地 $ 1#
     * from_lat $ string $ 12.33 $ 出发地纬度 $ 1#
     * from_lon $ string $ 12.33 $ 出发地经度 $ 1#
     * estimate_mileage $ string $ 12.6 $ 公里数 $ 1#
     * booking_type $ string $ 1 $ 订车类型：1，订车（日常）。2，包车。3，分时租赁 $ 1#
     * appointment_time $ string $ 2017-07-17 12：05：05 $ 预约时间#
     * pay_type $ string $ 1 $ 2-单位支付 3-财政支付,order_type=1#
     * approval_id $ int $ 1 $ 审核人id order_type=1时必填 #
     * approval_name $ string $ 1 $ 审批人 order_type=1时必填#
     * use_explain $ string $ 1 $ 用车说明 order_type=1#
     * use_type $ string $ 1 $ order_type=1 用车类型 1：行政执法，2：特殊公务，3：重要会议，4：机要通讯，5：视察调研，6：公务接待#
     * is_return $ string $ 1 $ booking_type=1，1-需要返程  9-无需#
     * to_addr $ string $ 晋江 $ booking_type=1，目的地#
     * to_lat $ string $ 12.12 $ booking_type=1，目的地纬度#
     * to_lon $ string $ 12.12 $ booking_type=1，目的地经度#
     * pre_meter $ string $ 12.12 $ 预计xx米 $ 1#
     * pre_time $ string $ 12.12 $ 预计时间 $ 1#
     * reorder $ int $ 0 $ 是否续单 0为否 续单请求下传原单id #
     * pre_fee $ string $ 12.12 $ 预计费用 $ 1
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息#
     * data $ string $ $ 列表 #{"from_addr":"1","from_lon":"1","from_lat":"1","plan_time":"2018-03-20 16:30","call_time":"2018-03-22 09:27:46","order_id":"26343","order_no":"201803220927461267242426"}
     * 】
     */
    public function orderApply()
    {

        $string = 'car_type_id|0#车型@require|number/order_type#订单类型@require|number/';
        $string.= 'passenger_name#乘客姓名@require|chsDash/passenger_phone#乘客电话@require|number|length:11/';
        $string.= 'booking_type|1#预定类型@require|number/is_return#返程@number/reorder|0#续单@number/';
        $string.= 'passenger_id#乘客ID@require/pay_type#支付类型@require|number/orderer_name||orderer#下单人@require';
        $data   = $this->getBatchParam($string);
        /* 前台直接传入 2018年5月18日 20:33:37
        $where['type']      = $data['order_type'] == 2 ? 3 + $data['booking_type'] : $data['order_type'] + $data['booking_type'];
        $where['car_type']  = $data['car_type'];
        unset($data['car_type']);
        $data['car_type_id']= Db::name('car_type')->where($where)->value('car_type_id');*/
        $data['area_id']        = 4;
        $data['company_id']     = (new model\Passenger())->where('passenger_id',$data['passenger_id'])->value('company_id');
        $string                 = 'from_addr#出发地@require/from_lon#出发经度@require|float/from_lat#出发纬度@require|float/appointment_time|-|plan_time#出发时间@require';
        $gpsData                = $this->getBatchParam($string);
        $gpsData['plan_time']   = $gpsData['plan_time'] > date('Y-m-d H:i:s') ? $gpsData['plan_time'] : date('Y-m-d H:i:s');
        $gpsData['call_time']   = date('Y-m-d H:i:s');
        $string                 = 'pre_meter|0#require|float/pre_time|0#require|float/pre_fee|0#require|float';
        $feeData                = $this->getBatchParam($string);
        $data['order_type'] == 3 && $data['order_state'] = 4;
        // 存在个人未支付订单 已派车订单，无法在使用个人订单
        if($data['order_type'] == 1){
            $data['order_state'] = 1;
            $data['apply_time']  = date('Y-m-d H:i:s', time());       //申请时间
            $string = 'pay_type#支付类型@require|number/approval_id#审核人ID@require|number/approval_name|-|approval#审核人@require|chsDash/';
            $string.= 'use_explain#用车说明@require/use_type#用车类型@number';
            $data1  = $this->getBatchParam($string);
            $data   = array_merge($data,$data1);
            $data['use_type'] = $data['pay_type'] == 2 ? 0 : $data['use_type'];
        }
        if($data['booking_type']==1){
            $string   = 'to_addr#目的地@require/to_lon#目的经度@require|float/to_lat#目的纬度@require|float';
            $gpsData1 = $this->getBatchParam($string);
            $gpsData  = array_merge($gpsData,$gpsData1);
        }
        if(!($data['booking_type'] == 1 && $data['order_type'] == 1)){
            unset($data['is_return']);
        }
        list($code, $msg)   = (new \app\api\logic\Order())->createOrder($data, $gpsData, $feeData);
        if($code==1){
            return $this->retSucc();
        }else{
            return $this->retError($msg);
        }
    }

    /**
     * @name【2.3 获取订单】
     * @desc【】
     * @method【post】
     * @table【p_order】
     * @param【_list】
     * @return【】
     * @table 【order,order_fee,order_gps,order_pay】
     */
    public function getOrder()
    {
        $joins = ['car','driver','area','company','fee','gps'];
        $data = [];
        //调用集成
        $data['count'] = $this->getCountCommon(new model\Order(),$joins);
        $data['data'] = $data['count'] ? $this->getListOrAll(new model\Order(),$joins) : [];
//        halt(1);
        return $this->res($data);
    }

    /**
     * @name【2.4获取订单预计费用】
     * @desc【获取订单预计费用】
     * @uri【getOrderPreFee】
     * @method【post】
     * @table【p_order,p_car_type】
     * @param【
     * token $ string $ abc $ 验证字符 $ 1 #
     * uid $ int $ 1 $ 用户id $ 1 #
     * car_type_id $ int $ 1 $ 车型id $ 1 #
     * estimate_mileage $ string $ 1 $ 公里数 $ 1 #
     * estimate_time $ int $ 1 $ 用时间秒 #
     * order_type $ string $ 1 $ 订单类型 $ 1 #
     * is_return $ string $ 1 $ order_type=1,是否往返
     * 】
     * @return【
     * code $ int $ number|1-1 $ 标识1-成功 0-失败#
     * msg $ string $  $ code=0，错误信息
     * 】
     */
    public function getOrderPreFee(){
        $car_type_id = input('car_type_id',0);
        $string   = 'estimate_mileage|0|mile#里程@require|float/estimate_time|0|time#时间@number/is_return|9#是否返程@require|in:1,9';
        $data     = $this->getBatchParam($string);
        $car_info = (new model\CarType())->where('car_type_id',$car_type_id)->where('state',1)->whereNull('delete_time')->find();
        if (!$car_info) {
            return $this->retError('无该车辆类型/已停用！');
        }
        $cost_info = (new \app\api\model\OrderFee())->countPreFee($car_info,$data['mile']*1000,$data['time'],$data['is_return']);
        $code      = empty($cost_info) ? 0 : 1;
        $msg       = empty($cost_info) ? '计算车费出错' : $cost_info;
        if($code==1){
            $dataBack['data'] = $msg;
            $string = 'starting_price|起步价,estimate_cost|预计费用';
            $dataBack['description'] = analyzeDesc($string);
            return $this->retSucc($dataBack);
        }else{
            return $this->retError($msg);
        }
    }

    /**
     * @name【2.5 取消订单】
     * @desc【】
     * @method【post】
     * @allow【order_id,order_state】
     * @param【
     * order_id $ int $ 123 $ 订单ID  $ 1 #
     * close_chcek $ int $ 1 $ 输入1做为确认 $ 1 #
     * 】
     * @return【
     *
     * 】
     * @table 【order】
     * @throws
     */
    public function closeOrder()
    {
        $param = $this->getParam(new validate\OrderValidate(),'close');
        if($param['close_chcek'] == '1') {
            $order = (new model\Order())->get($param['order_id']);
            //更改状态
            $order->order_state = '12';
            $rslt = $order->save();
            $rslt['msg'] = '成功';
        }
        else{
            $rslt['msg'] = '失败,缺close_chcek#1';
        }
        return $this->res($rslt);
    }

    /**
     * @name【3.1北斗车辆列表】
     * @desc【北斗车辆列表】
     * @uri【getCars】
     * @method【post】
     * @table【p_car】
     * @param【
     * token $ string $  $ token  #
     * company_id $ int $  $ 公司id #
     * car_number $ string $  $ 车牌
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息
     * 】
     */
    public function getCars()
    {
        $validate = new BeidouValidate();
        $whereData = $validate->goCheck()->getCurrentData();
        $cars = $this->getRedisData();
        if (!$cars) {
            return $this->retError('数据请求异常，请重新发起请求。');
        }
        $numbers = array_column($cars, null, 'carno');
        $data = [];
        if(isset($whereData['company_id'])){
            $whereData['entrust_company_id|company_id'] = $whereData['company_id'];
            unset($whereData['company_id']);
        }
        $list = (new model\Car())->field('car_id,number,entrust_company_id,company_id')->whereNull('delete_time')->where($whereData)->select();
        foreach ($list AS $id => $value) {
            $beidou = $numbers[$value['number']];
            $value['loc'] = [$beidou['lon'], $beidou['lat']];
            //没有位置信息的时候生成随机位置by yulin
            if(!$beidou['lon'] && !$beidou['lat']){
                $value['loc'] = ['118.'.mt_rand(40000,60000),'24.'.mt_rand(68000,92000)];
            }
            $states = explode(' ', trim($beidou['state']));
            switch ($states[0]) {
                case '停止':
                    $value['state'] = 1;
                    break;
                case '行驶':
                    $value['state'] = 2;
                    break;
                case '':
                    $value['state'] = 4;
                    break;
            }
            if ($states[1] == '离线') $value['state'] = 3;
            $value['alarm'] = $beidou['alarm'];
            $value['time'] = date('Y-m-d H:i', $beidou['time']);
            $data[$id] = $value;
        }
        return $this->retSucc(['data' => $data]);
    }

    /**
     * @name【3.2获取北斗轨迹】
     * @desc【获取北斗轨迹】
     * @uri【getTrack】
     * @method【post】
     * @table【】
     * @param【
     * token $ string $ abc $ token $ 1 #
     * company_id $ int $ 110 $ 公司id #
     * car_number $ string $ 闽CA123 $ 车牌
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息
     * 】
     */
    public function getTrack()
    {
        $oid = input('oid', 0);
        return (new \app\api\model\Order())->getTrack($oid);
    }

    /**
     * @name【4.1乘客列表】
     * @desc【乘客列表】
     * @uri【passengerList】
     * @method【post】
     * @table【p_passenger,p_company,p_department】
     * @param【
     * token $ string $  $ 验证字符  #
     * uid $ int $  $ 用户id  #
     * fields $ string $  $ 字段名称 #
     * where_json $ json $ {"order_id":["in","6,7,8"],"name":["like","%王%"]} $ 查询条件 #
     * page $ int $ 1$ 页数 #
     * pagenum $ int $ 10 $记录数
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息 #
     * data $ json $ $ 订单列表 #
     * description $ json $ $ 接口说明
     * 】
     */
    public function passengerList(){
        $report = new Report();
        $param  = $report->scene('report')->getCurrentData();
        $report->goCheck($param);
        $where     = json_decode($param['where_json'],true);
        $fields     = json_decode($param['fields'],true);
        $page     = json_decode($param['page'],true);
        $pagenum     = json_decode($param['pagenum'],true);

        $data['data'] = (new model\Passenger())
            ->alias('a')
            ->join('company b','a.company_id = b.company_id','left')
            ->join('department c','a.department_id = c.department_id','left')
            ->field('a.*,b.*,c.department_id,c.company_id')
            ->where($where)
            ->page($page,$pagenum)
            ->select();

        $data['count'] = (new model\Passenger())
            ->alias('a')
            ->join('company b','a.company_id = b.company_id','left')
            ->join('department c','a.department_id = c.department_id','left')
            ->where($where)
            ->count();


        return $this->res($data);
    }

    /**
     * @name【5.1公司列表】
     * @desc【公司列表】
     * @uri【companyList】
     * @method【post】
     * @table【p_passenger,p_company,p_department】
     * @param【
     * token $ string $  $ 验证字符  #
     * uid $ int $  $ 用户id  #
     * fields $ string $  $ 字段名称 #
     * where_json $ json $ {"order_id":["in","6,7,8"],"name":["like","%王%"]} $ 查询条件 #
     * page $ int $ 1$ 页数 #
     * pagenum $ int $ 10 $记录数
     * 】
     * @return【
     * code $ int $ number|1-1 $ 校验码#
     * msg $ string $  $ 错误信息 #
     * data $ json $ $ 订单列表 #
     * description $ json $ $ 接口说明
     * 】
     */
    public function companyList(){
        $report = new Report();
        $param  = $report->scene('report')->getCurrentData();
        $report->goCheck($param);
        $where     = json_decode($param['where_json'],true);
        $fields     = json_decode($param['fields'],true);
        $page     = json_decode($param['page'],true);
        $pagenum     = json_decode($param['pagenum'],true);

        $data['data'] = (new model\Company())
            ->field($fields)
            ->where($where)
            ->page($page,$pagenum)
            ->select();

        $data['count'] = (new model\Company())
            ->where($where)
            ->count();


        return $this->res($data);
    }
}